'use strict';

const Service = require('egg').Service;
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

class AccountService extends Service {
    // 查询注册验证码
    async getRegEmailCode(data) {
      const { ctx } = this;
      let config = {
        where:{
          email:data.email,
          type:1
        },
        order:[
            ['id', 'DESC']
        ]
      };
      return await ctx.model.Emailcode.findOne(config);
    }

    // 保存注册验证码
    async saveRegEmailCode(data) {
        const { ctx } = this;
        const t = await ctx.model.transaction();
        try {
          let updateResult = await ctx.model.Emailcode.update({
              isInvalid: 1
            }, {
              where: {
                type: 1,
                email: data.email
              },
              transaction: t
            }
          );
          let createResult = await ctx.model.Emailcode.create({
            email: data.email,
            code: data.code,
            type: 1,
            pushTime: new Date().getTime(),
            verifyTime: new Date().getTime() + (1000 * 60 * 30)
          },{
            transaction: t
          });
          if(!createResult.id){
            throw new Error('error');
          }
          await t.commit();
          return createResult;
        }catch(e){
          await t.rollback();
          return {id:0};
        }
    }

    // 根据邮箱获取用户
    async getEmaildetail(query) {
        const { ctx } = this;
        let config = {
          where:{
            isDel:0,
            email:query.email
          },
          attributes: ['id']
        };
        return await ctx.model.User.findOne(config);
    }

    // 注册
    async register(data) {
        const { ctx } = this;
        return await ctx.model.User.create({
            account:data.email,
            email:data.email,
            password:data.password,
            nickname:data.nickname,
            createTime:new Date().getTime(),
            updateTime:new Date().getTime(),
            delTime:0
        });
    }

    // 登录
    async login(data) {
        const { ctx } = this;
        let config = {
            where:{
                isDel:0,
                account:data.account,
                password:data.password
            },
            attributes: ['id','status']
        };
        return await ctx.model.User.findOne(config);
    }

    // 账号详情
    async getInfo() {
        const { ctx } = this;
        let config = {
            where:{
                isDel:0,
                id:ctx.request.header.uid
            },
            attributes: {
              include: [
                [
                  Sequelize.literal(`(
                        SELECT COUNT(*)
                        FROM collection
                        WHERE
                            collection.uid = user.id
                            AND
                            collection.type = 1
                    )`),
                  'collectionMusicNum'
                ],
                [
                  Sequelize.literal(`(
                        SELECT COUNT(*)
                        FROM collection
                        WHERE
                            collection.uid = user.id
                            AND
                            collection.type = 2
                    )`),
                  'collectionStarNum'
                ],
                [
                  Sequelize.literal(`(
                        SELECT COUNT(*)
                        FROM collection
                        WHERE
                            collection.uid = user.id
                            AND
                            collection.type = 3
                    )`),
                  'collectionAlbumNum'
                ],
                [
                  Sequelize.literal(`(
                        SELECT COUNT(*)
                        FROM collection
                        WHERE
                            collection.uid = user.id
                            AND
                            collection.type = 4
                    )`),
                  'collectionPlaylistNum'
                ],
                [
                  Sequelize.literal(`(
                        SELECT COUNT(*)
                        FROM likes
                        WHERE
                            likes.uid = user.id
                    )`),
                  'likesNum'
                ],
                [
                  Sequelize.literal(`(
                        SELECT COUNT(*)
                        FROM comment
                        WHERE
                            comment.uid = user.id
                            AND
                            comment.isDel = 0
                            AND
                            comment.status = 1
                    )`),
                  'commentNum'
                ],
                [
                  Sequelize.literal(`(
                        SELECT COUNT(*)
                        FROM playlist
                        WHERE
                            playlist.uid = user.id
                            AND
                            playlist.isDel = 0
                    )`),
                  'playlistNum'
                ],
              ],
              exclude: ['isDel','delTime','status','password','createTime','updateTime'],
            },
        };
        return await ctx.model.User.findOne(config);
    }

    // 账号信息修改
    async editInfo(data) {
      const { ctx } = this;
      return await ctx.model.User.update({
        nickname:data.nickname,
        headimg:data.headimg?data.headimg:'',
        updateTime:new Date().getTime()
      },{
        where:{
          id:ctx.request.header.uid
        }
      });
    }

    // 修改密码
    async editPassword(data) {
      const { ctx } = this;
      return await ctx.model.User.update({
        password:data.password,
        updateTime:new Date().getTime()
      },{
        where:{
          id:ctx.request.header.uid
        }
      });
    }

    // 查询注册验证码
    async getFindEmailCode(data) {
      const { ctx } = this;
      let config = {
        where:{
          email:data.email,
          type:2
        },
        order:[
          ['id', 'DESC']
        ]
      };
      return await ctx.model.Emailcode.findOne(config);
    }

    // 保存找回密码验证码
    async saveFindEmailCode(data) {
      const { ctx } = this;
      const t = await ctx.model.transaction();
      try {
        let updateResult = await ctx.model.Emailcode.update({
            isInvalid: 1
          }, {
            where: {
              type: 2,
              email: data.email
            },
            transaction: t
          }
        );
        let createResult = await ctx.model.Emailcode.create({
          email: data.email,
          code: data.code,
          type: 2,
          pushTime: new Date().getTime(),
          verifyTime: new Date().getTime() + (1000 * 60 * 30)
        },{
          transaction: t
        });
        if(!createResult.id){
          throw new Error('error');
        }
        await t.commit();
        return createResult;
      }catch(e){
        await t.rollback();
        return {id:0};
      }
    }

    // 找回密码
    async findPassword(data) {
      const { ctx } = this;
      return await ctx.model.User.update({
        password:data.password,
        updateTime:new Date().getTime()
      },{
        where:{
          email:data.email
        }
      });
    }
  }

  module.exports = AccountService;
